package com.luo.demo;

import com.alibaba.fastjson.JSON;
import com.luo.mapper.UserMapper;
import com.luo.pojo.Announcement;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/homePageAddAnnServlet")
public class HomePageAddAnnDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json;charset=utf-8");
        req.setCharacterEncoding("UTF-8");

        // 获取请求体数据
        BufferedReader br = req.getReader();
        String params = br.readLine();

        // 将JSON字符串转为Java对象
        Announcement announcement = JSON.parseObject(params, Announcement.class);

        //2. 调用service 添加
        SqlSession session = util00.useSqlSessionFactory().openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        Integer integer = mapper.addAnnouncement(announcement.getAnnTitle(), announcement.getAnnContent(), announcement.getAnnDate());

        if (integer == 1){
            session.commit();
            resp.getWriter().write("添加成功");
        }else {
            resp.getWriter().write("添加失败");
        }
        session.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
